package com.tul.exercise.base.swing.components;

import com.tul.exercise.base.swing.SwingConsole;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @Description 《java编程思想》第22章 示例16：
 * <p>
 * 列表框
 **/
public class JListTest extends JFrame {

    private String[] flavors = {"Chocolate", "Strawberry",
            "Vanilla", "Mint Chip", "Mocha Almond Fudge", "Rum Raisin", "Mud Pie"};

    private DefaultListModel lItems = new DefaultListModel();

    private JList list = new JList(lItems);
    private JTextArea textArea = new JTextArea(flavors.length, 20);
    private JButton addItem = new JButton("Add Item");

    private int count = 0;
    private ActionListener bl = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (count < flavors.length) {
                lItems.add(0, flavors[count++]);
            } else {
                addItem.setEnabled(false);
            }
        }
    };

    private ListSelectionListener ll = new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
                return;
            }

            textArea.setText("");

            for (Object item : list.getSelectedValues()) {
                textArea.append(item + "\n");
            }
        }
    };

    public JListTest() {
        textArea.setEnabled(false);
        setLayout(new FlowLayout());
        Border brd = BorderFactory.createMatteBorder(1, 1, 2, 2, Color.BLACK);
        list.setBorder(brd);

        for (int i = 0; i < flavors.length - 2; i++) {
            lItems.addElement(flavors[count++]);
        }

        add(textArea);
        add(list);
        add(addItem);

        list.addListSelectionListener(ll);
        addItem.addActionListener(bl);
    }

    public static void main(String[] args) {
        SwingConsole.run(new JListTest(), 250, 375);
    }
}
